package android.musicplayer.home;

import java.io.IOException;
import java.util.ArrayList;

import android.app.ListActivity;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class MusicList extends ListActivity {
	int pp;
	ArrayAdapter<String> adapter;
	ArrayList<String> mUriArrayList;
	Cursor cursor;
	MediaPlayer mps;
	
	String[] projection = {
	MediaStore.Audio.Media._ID,
	MediaStore.Audio.Media.ARTIST,
	MediaStore.Audio.Media.TITLE,
	MediaStore.Audio.Media.DATA,
	MediaStore.Audio.Media.DISPLAY_NAME,
	MediaStore.Audio.Media.DURATION
	};

	String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.musiclist);

		pp=-1;
		mps = new MediaPlayer();
		cursor = this.managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);

		this.setAdapter();
		initArray();
	}

	private void initArray() {
		mUriArrayList = new ArrayList<String>();
		while (cursor.moveToNext()) {
			String uri = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA));
			//Log.i("CTO", uri);
			mUriArrayList.add(uri);
		}
		
	}

	private void setAdapter() {
		 String[] from = {MediaStore.Audio.AudioColumns.TITLE,  
	                MediaStore.Audio.AudioColumns.ARTIST};  
	        int[] to = {android.R.id.text1,android.R.id.text2};  
	        final CursorAdapter adapter = new SimpleCursorAdapter(this,  
	                android.R.layout.simple_list_item_2,cursor,   
	                from, to); 
	        this.setListAdapter(adapter);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
			 Log.i("CTO", mUriArrayList.get(position));
			 mps.reset();
			 try {
				mps.setDataSource(mUriArrayList.get(position-1));
				mps.prepare();
				mps.start();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			 
	}

}
